package com.gientech.gateway.controller;

import javax.annotation.Resource;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.boot.web.client.RestTemplateCustomizer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class GateWayDemoController {
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    RestTemplate restTemplate;

    public GateWayDemoController() {
    }

    @GetMapping({"/{serverAName}/{interfaceName}"})
    public String myGateway(@PathVariable("serverAName") String servername, @PathVariable("interfaceName") String interfacename) {
        String url = (String)this.redisTemplate.opsForValue().get(servername);
        if (url != null && !url.equals("")) {
            String target = url + "/" + interfacename;
            System.out.println("- 目标服务：" + target);
            RestTemplate restTemplate = (new RestTemplateBuilder(new RestTemplateCustomizer[0])).build();
            String response = (String)restTemplate.getForObject(target, String.class, new Object[0]);
            System.out.println("- 访问目标服务：" + response);
            return "访问目标服务:" + response == null ? "访问失败" : response;
        } else {
            return "未找到服务：【" + servername + "】";
        }
    }

    @GetMapping({"/setService/{serviceName}"})
    public String providder(@PathVariable("serviceName") String servername) {
        String value = "http://127.0.0.1:8001/";
        this.redisTemplate.opsForValue().set(servername, value);
        return "redis存入:" + servername + ": " + value;
    }
}
